
const http = require('http')
const url = require('url')
const { parse } = require('path')
const util = require('util')
const querystring = require('querystring')

var server = http.createServer((req, res) => {
    // 解决中文乱码问题
    //res.setHeader("content-type", "text/html; charset=utf-8");

    // 解决跨域问题
    res.setHeader("Access-Control-Allow-Origin", "*")

    // 接受自定义请求头
    //res.setHeader("Access-Control-Allow-Headers", "*")
    // ...

    var body = ""

    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    req.on('data', function (chunk) {
        body += chunk; //一定要使用+=，如果body=chunk，因为请求favicon.ico，body会等于{}
        console.log(">>>>>>>>>> chunk:", chunk.toString());
    });

    req.on('end', function () {
        //body = querystring.parse(body)
        console.log('post body:', body)
        res.end(util.inspect(body))
    })

    res.write('<h1>Hello World!</h1>')
    //res.writeHead(200, {'Content-Type': 'text/plain'})

    const parseInfo = url.parse(req.url, true)  //true:解析为对象 false:保留字符串
    console.log("recv req:", req)
    console.log("recv parseInfo:", parseInfo)
    console.log("recv parseInfo.query:", parseInfo.query)
    if (body == '') {
        res.end("rcv:" + util.inspect(parseInfo.query))
    }
})

server.listen(8899, "0.0.0.0", () => {
    console.log("server listen  是 ok")
})


//process.exit(1)

